from django.db import transaction
from rest_framework import serializers

from apps.goods.models import SKU, SKUSpecification, GoodsCategory
from celery_tasks.detail.tasks import generate_task


class SKURealted(serializers.Serializer):
    spec_id=serializers.IntegerField()
    option_id=serializers.IntegerField()


# SKU
class SKUModel(serializers.ModelSerializer):
    spu=serializers.StringRelatedField(read_only=True)
    spu_id=serializers.IntegerField()
    category_id=serializers.IntegerField()
    category=serializers.StringRelatedField(read_only=True)
    specs=SKURealted(many=True)
    class Meta:
        model=SKU
        fields='__all__'

    def create(self, validated_data):
        with transaction.atomic():
            sid=transaction.savepoint()
            try:
                spec=self.context['request'].data.get('specs')
                validated_data.pop('specs')
                sku=super().create(validated_data)
                for i in spec:
                    i['sku_id']=sku.id
                    SKUSpecification.objects.create(**i)

            except Exception as e:
                transaction.savepoint_rollback(sid)
                raise e
            else:
                transaction.savepoint_commit(sid)
                print(sku.id)
                generate_task.delay(sku.id)
                return sku


    def update(self, instance, validated_data):
        with transaction.atomic():
            sid=transaction.savepoint()
            try:
                specs=validated_data.pop('specs')

                sku=super().update(instance,validated_data)

                #删掉规格表里对应的数据源
                SKUSpecification.objects.filter(sku_id=instance.id).delete()
                for i in specs:
                    i['sku_id']=instance.id
                    SKUSpecification.objects.create(**i)
            except Exception as e:
                transaction.savepoint_rollback(sid)
                raise e
            else:
                transaction.savepoint_commit(sid)

                generate_task.delay(sku.id)
                return sku


class ThirdCategory(serializers.ModelSerializer):
    class Meta:
        model=GoodsCategory
        fields=['id','name']


class SKUidModel(serializers.ModelSerializer):
    class Meta:
        model=SKU
        fields=['id','name']